package org.example.computerdesign.service.imp;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.computerdesign.common.constants.CommonRedisKeyConstant;
import org.example.computerdesign.domain.po.Doctor;
import org.example.computerdesign.domain.vo.DoctorV;
import org.example.computerdesign.exception.ServiceException;
import org.example.computerdesign.mapper.DoctorMapper;
import org.example.computerdesign.service.DoctorService;
import org.example.computerdesign.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * @author 朱文权
 * */
@Service
public class DoctorServiceImp extends ServiceImpl<DoctorMapper, Doctor>implements DoctorService {
    @Autowired
    private DoctorMapper doctorMapper;
    @Override
    public String login(String email, String password) {
        Doctor doctor=doctorMapper.selectByEmail(email);
        if(doctor==null){
            throw new ServiceException("该账号不存在",400);
        }
        String encrypt=DigestUtil.sha256Hex(password);
        if(!encrypt.equals(doctor.getPassword())){
            throw new ServiceException("密码错误",400);
        }
        //登录
        StpUtil.login(doctor.getId());
        return StpUtil.getTokenValue();
    }

    @Override
    public void register(String email, String password, String code) {
        //先判断数据库有无该账号
        Doctor doctor=doctorMapper.selectByEmail(email);
        if(doctor!=null){
            throw new ServiceException("该账号已注册",400);
        }
        //判断验证码是否存在
        String verify= (String)RedisUtil.get(CommonRedisKeyConstant.EMAIL_REGISTER_KEY+email);
        if(verify==null){
            throw new ServiceException("验证码不存在或者已过期",400);
        }
        //判断验证码是否正确
        if(!code.equals(verify)){
            throw new ServiceException("验证码不正确",400);
        }
        //对密码进行散列函数加密
        String encrypt= DigestUtil.sha256Hex(password);
        //创建对象并插入数据库
        doctor=new Doctor();
        doctor.setEmail(email)
                .setName("医生")
                .setPassword(encrypt);
        doctorMapper.insert(doctor);
        //删除redis键
        RedisUtil.del(CommonRedisKeyConstant.EMAIL_REGISTER_KEY+email);
    }

    @Override
    public DoctorV getDoctorInfo(Long id) {
        Doctor doctor = doctorMapper.selectById(id);
        return BeanUtil.copyProperties(doctor, DoctorV.class);
    }
}
